package com.salesmanager.core.business.app.dao;

import com.salesmanager.core.base.QueryResult;
import com.salesmanager.core.base.QueryResultJPAImpl;
import com.salesmanager.core.business.app.model.AndroidChannel;
import com.salesmanager.core.business.generic.dao.SalesManagerEntityDaoImpl;
import com.salesmanager.core.business.statistics.model.AppChannelCriteria;
import com.salesmanager.web.model.paging.PaginationDataList;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Liutong on 2016/1/13.
 */
@Repository("appChannelDao")
public class AppChannelDaoImpl extends SalesManagerEntityDaoImpl<Long,AndroidChannel> implements AppChannelDao {


    public AppChannelDaoImpl(){super();}

    @Override
    public PaginationDataList<AndroidChannel> getAppChannelList(AppChannelCriteria criteria) {
        StringBuilder sql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        sql.append("SELECT AC.CHANNEL_ID,AC.CHANNEL_CODE,AC.CHANNEL_NAME,AC.VERSION,AC.FILE_NAME,AC.FILE_SIZE FROM ANDROID_CHANNEL AC WHERE 1=1 ");
        countSql.append("SELECT COUNT(*) FROM ANDROID_CHANNEL AC WHERE 1=1 ");
        if (!StringUtils.isBlank(criteria.getChannelCode())){
            whereSql.append("AND AC.CHANNEL_CODE = :code ");
        }
        if (!StringUtils.isBlank(criteria.getChannelName())){
            whereSql.append("AND AC.CHANNEL_NAME like :name ");
        }
        Query query = super.getEntityManager().createNativeQuery(sql.append(whereSql).toString());
        Query countQuery = super.getEntityManager().createNativeQuery(countSql.append(whereSql).toString());

        //分页
        if (criteria.getMaxCount() > 0){
            query.setMaxResults(criteria.getMaxCount());
            query.setFirstResult(criteria.getStartIndex());
        }
        if (!StringUtils.isBlank(criteria.getChannelCode())){
            query.setParameter("code", criteria.getChannelCode());
            countQuery.setParameter("code", criteria.getChannelCode());
        }
        if (!StringUtils.isBlank(criteria.getChannelName())){
            query.setParameter("name","%"+criteria.getChannelName()+"%");
            countQuery.setParameter("name","%"+criteria.getChannelName()+"%");
        }
        PaginationDataList<AndroidChannel> result = new PaginationDataList<AndroidChannel>();
        //总数
        Number totalCount = (Number)countQuery.getSingleResult();
        result.setTotalCount(totalCount.intValue());
        List lists = query.getResultList();
        List<AndroidChannel> data = new ArrayList<AndroidChannel>();
        for(int i=0;i<lists.size();i++){
            Object[] o = (Object[]) lists.get(i);
            AndroidChannel androidChannel = new AndroidChannel();
            androidChannel.setId(Long.parseLong(o[0].toString()));
            androidChannel.setChannelCode((String)o[1]);
            androidChannel.setChannelName((String)o[2]);
            androidChannel.setVersion((String)o[3]);
            androidChannel.setFileName((String)o[4]);
            androidChannel.setFileSize((Integer) o[5]);
            data.add(androidChannel);
        }
        result.setData(data);
        return result;
    }

    @Override
    public AndroidChannel getByChannelCode(String channelCode) {//hql语句
        String hql = "select ac from AndroidChannel ac where ac.status = 1 and ac.channelCode = :channelCode";
        Query query = super.getEntityManager().createQuery(hql);
        query.setParameter("channelCode",channelCode);
        AndroidChannel androidChannel = null;
        try {
            androidChannel = (AndroidChannel)query.getSingleResult();
        } catch (NoResultException e){

        }
        return androidChannel;
    }

    @Override
    public void deleteById(Long channelId) {
        StringBuilder sql = new StringBuilder();
        sql.append("DELETE AC FROM ANDROID_CHANNEL AC WHERE AC.CHANNEL_ID = :id");
        Query query = super.getEntityManager().createNativeQuery(sql.toString());
        query.setParameter("id",channelId);
        query.executeUpdate();
    }

    @Override
    public List<AndroidChannel> getChannelCodes() {
        StringBuilder sql = new StringBuilder();
        List<AndroidChannel> list = new ArrayList<AndroidChannel>();
        sql.append("SELECT A.CHANNEL_ID, A.CHANNEL_CODE FROM ANDROID_CHANNEL A WHERE 1=1 ");
        Query query = super.getEntityManager().createNativeQuery(sql.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        QueryResult rs = new QueryResultJPAImpl(query.getResultList());
        while (rs.next()){
            AndroidChannel androidChannel = new AndroidChannel();
            androidChannel.setId(rs.getLong("CHANNEL_ID"));
            androidChannel.setChannelCode(rs.getString("CHANNEL_CODE"));
            list.add(androidChannel);
        }
        return list;
    }
}
